using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using UMC.Data;
using UMC.Data.Entities;
using UMC.Host;
using UMC.Net;
using UMC.ITME.Entities;
using UMC.Security;
using UMC.Web;
using UMC.Web.UI;


namespace UMC.ITME.Activities
{
    [Apiumc("ITME", "Server", Auth = WebAuthType.Admin, Desc = "Http服务配置")]
    public class SiteServerActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var hosts = UMC.Data.Reflection.Configuration("host");
            var model = this.AsyncDialog("Model", akey =>
            {

                var ui = UISection.Create(new UITitle("网络服务"));

                var unix = hosts.Providers.Where(r => r.Type == "unix");

                var provider = Data.WebResource.Instance().Provider;
                ui//.AddCell("主协议", provider["scheme"] ?? "http", new UIClick(request.Model, request.Command, "Domain"))
               .AddCell("根域名", provider["domain"] ?? "未设置", new UIClick(request.Model, request.Command, "Domain"));

                var authDomain = provider["auth"];
                if (String.IsNullOrEmpty(authDomain))
                {
                    ui.AddCell("主域名", provider["domain"], new UIClick(request.Model, request.Command, "AuthDomain"));
                }
                else
                {

                    ui.AddCell("主域名", String.Format("{0}{1}{2}", authDomain, provider["union"] ?? ".", provider["domain"]), new UIClick(request.Model, request.Command, "AuthDomain"));
                }
                var assist = ui.NewSection()
                .AddCell("辅助域名", new UIClick(request, "Assist"));


                var asshosts = HotCache.Find(new SiteHost { Root = StringValue.Empty });
                foreach (var ass in asshosts)
                {
                    var cell = UI.UI(ass.Host.ToString(), ass.IsAuthModel == true ? "不检验" : "");// $"{type}:{em.Current.Value.Item3[0]}");//.ToString());
                    assist.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "DelAssist", "Domain", ass.Host.ToString())));

                }



                var dnsUI = ui.NewSection()
                .AddCell("DNS", new UIClick(request, "DNS"));

                var em = UMC.Net.NetProxy.DNS().GetEnumerator();
                while (em.MoveNext())
                {
                    if (em.Current.Value.Item2.HasFlag(NetProxy.DNSType.DNS))
                    {
                        var type = em.Current.Value.Item2.HasFlag(NetProxy.DNSType.IP6) ? "IPDNS6" : "IPDNS";
                        if (em.Current.Value.Item3.Length > 0)
                        {
                            var cell = UI.UI(em.Current.Key, $"{type}:{em.Current.Value.Item3[0]}");//.ToString());
                            dnsUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "DelDNS", "Domain", em.Current.Key)));
                        }
                        else
                        {
                            var cell = UI.UI(em.Current.Key, type);//.ToString());
                            dnsUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "DelDNS", "Domain", em.Current.Key)));
                        }
                    }
                    else if (em.Current.Value.Item1 == int.MaxValue && em.Current.Value.Item3.Length > 0)
                    {

                        var cell = UI.UI(em.Current.Key, em.Current.Value.Item3[0].ToString());
                        dnsUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "DelDNS", "Domain", em.Current.Key)));

                    }
                }
                var qpsUI = ui.NewSection();
                qpsUI.AddCell("QPS", new UIClick(request, "QPS"));

                var em2 = UMC.Net.NetProxy.Pool.GetEnumerator();
                while (em2.MoveNext())
                {
                    if (em2.Current.Value.Qps > 0)
                    {
                        qpsUI.Add(UI.UI(em2.Current.Key, em2.Current.Value.Qps.ToString(), em2.Current.Value.Semaphore.CurrentCount.ToString()));

                    }
                }

                var http = hosts.Providers.Where(r => r.Type == "http");

                var httpUI = ui.NewSection();
                httpUI.AddCell("HTTP", new UIClick(request, "Http"));
                if (http.Count() > 0)
                {
                    foreach (var p in http)
                    {
                        var cell = UI.UI("端口", p.Attributes["port"] ?? "80");
                        httpUI.Delete(cell, new UIEventText().Click(new UIClick(request, p.Name)));
                    }
                }

                var https = hosts.Providers.Where(r => r.Type == "https");
                var httpsUI = ui.NewSection();
                httpsUI.AddCell("HTTPS", new UIClick(request, "Https"));
                if (https.Count() > 0)
                {
                    foreach (var p in https)
                    {
                        var cell = UI.UI("端口", p.Attributes["port"] ?? "80");//, new UIClick(p.Name).Send(request.Model, request.Command));
                        httpsUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, p.Name, "Type", "Del")));
                    }
                }



                var sslUI = ui.NewSection();

                sslUI.AddCell("证书", new UIClick(request, "Cert"));
                var now = UMC.Data.Utility.TimeSpan();

                var lr = new Dictionary<string, Certificater>(Certificater.Certificates);

                var certs = HotCache.Find(new SiteCert { }, false, 0, 500, out var nextIndex);
                foreach (var r in certs)
                {
                    var cell = UI.UI(r.Domain.UTF8(), Utility.Expire(now, r.ExpirationTime ?? 0, "正签发"), new UIClick(request, akey, "CSR", "Domain", r.Domain.UTF8()));
                    sslUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "Del", "Domain", r.Domain.Span.UTF8())));
                    lr.Remove(r.Domain.UTF8());
                }
                var ls = lr.Values.OrderBy(r => r.Time);

                foreach (var r in ls)
                {
                    var cell = UI.UI(r.Name, Utility.Expire(now, r.Time, "正签发"), new UIClick(request, akey, "CSR", "Domain", r.Name));
                    sslUI.Delete(cell, new UIEventText().Click(new UIClick(request, akey, "Del", "Domain", r.Name)));
                }
                var proxyUI = ui.NewSection();

                proxyUI.AddCell("代理节点", new UIClick(request, "Proxy"));
                var proxy = UMC.Data.Reflection.Configuration("proxy");


                var defaultProxy = UMC.Data.Reflection.Configuration("host").Providers.FirstOrDefault(r => r.Type == "proxy") ?? Provider.Create("0", "proxy");

                var host = request.Url.Host;
                var limit = defaultProxy.Attributes["limit"];
                var port = defaultProxy.Attributes["port"] ?? "443";
                proxyUI.AddCell("本机代理", host, new UIClick(request, akey, "Proxy", "Proxy", "0"));


                if (proxy.Providers.Count > 0)
                {
                    foreach (var p in proxy.Providers)
                    {
                        limit = p.Attributes["limit"];
                        host = p.Name;//.Attributes["host"];
                        port = p.Attributes["port"] ?? "443";
                        var title = p.Attributes["title"] ?? String.Empty;// $"{host}:{port}";


                        if (String.IsNullOrEmpty(title))
                        {

                            proxyUI.Delete(UI.UI(host, new UIClick(request, akey, "Proxy", "Proxy", p.Name)), new UIEventText().Click(new UIClick(request, akey, "ProxyDel", "Proxy", p.Name)));


                        }
                        else
                        {
                            proxyUI.Delete(UI.UI(title, host, new UIClick(request, akey, "Proxy", "Proxy", p.Name)), new UIEventText().Click(new UIClick(request, akey, "ProxyDel", "Proxy", p.Name)));

                        }

                    }

                }


                ui.UIFootBar = new UIFootBar() { IsFixed = true };
                ui.UIFootBar.AddText(new UIEventText("申请免费证书").Click(new UIClick(request, "ApplyCert")),
                    new UIEventText("重新加载").Click(new UIClick("Http", "Bridge", "Reload")).Style(new UIStyle().BgColor()));

                ui.SendTo(this.Context, $"{request.Model}.{request.Command}");

                return this.DialogValue("none");
            });
            switch (model)
            {
                case "ProxyDel":

                    var proxyConfig2 = UMC.Data.Reflection.Configuration("proxy");
                    proxyConfig2.Remove(this.AsyncDialog("Proxy", "none"));
                    UMC.Data.Reflection.Configuration("proxy", proxyConfig2);
                    this.Context.Send($"{request.Model}.{request.Command}", true);
                    break;
                case "Proxy":
                    {
                        var proxyConfig = UMC.Data.Reflection.Configuration("proxy");
                        var porxy = this.AsyncDialog("Proxy", "New");


                        var setting = this.AsyncDialog("Config", r =>
                        {
                            var fm = new UIFormDialog() { Title = "代理节点" };
                            switch (porxy)
                            {
                                case "0":
                                    fm.Title = "代理服务";
                                    fm.AddTextValue().Put("代理名称", "本机代理");
                                    var defaultProxy = UMC.Data.Reflection.Configuration("host").Providers.FirstOrDefault(r => r.Type == "proxy");// ?? Provider.Create("proxy", "proxy");

                                    fm.AddText("转发节点", "Host", defaultProxy?["repost"]).NotRequired();//.Put("tip", String.Empty).NotRequired();
                                    fm.AddNumber("开放端口", "Port", defaultProxy?["port"]).NotRequired();
                                    fm.AddNumber("连续开放", "Limit", defaultProxy?["limit"]).NotRequired();
                                    break;
                                default:
                                    var pCfg = proxyConfig[porxy];

                                    if (pCfg != null)
                                    {
                                        fm.AddTextValue().Put("服务IP", pCfg?.Name);
                                        fm.AddText("代理名称", "Title", pCfg?["title"]);
                                        fm.AddNumber("节点端口", "Port", pCfg?["port"]);
                                        fm.AddNumber("连续数量", "Limit", pCfg?["limit"]).NotRequired();

                                    }
                                    else
                                    {
                                        fm.AddText("代理名称", "Title", pCfg?["title"]);
                                        fm.AddText("服务IP", "Host", pCfg?.Name).Put("tip", String.Empty);
                                        fm.AddNumber("节点端口", "Port", pCfg?["port"]);
                                        fm.AddNumber("连续数量", "Limit", pCfg?["limit"]).NotRequired();

                                    }
                                    break;
                            }
                            fm.Submit("确认", $"{request.Model}.{request.Command}");

                            return fm;
                        });
                        var host = setting["Host"];
                        if (String.IsNullOrEmpty(host) == false)
                        {
                            if (System.Net.IPAddress.TryParse(host, out var address) == false)
                            {
                                this.Prompt("只能是IP地址");
                            }
                        }
                        if (porxy == "0")
                        {
                            var configs = UMC.Data.Reflection.Configuration("host");
                            var defaultProxy = configs.Providers.FirstOrDefault(r => r.Type == "proxy") ?? Provider.Create("proxy", "proxy");

                            if (String.IsNullOrEmpty(host))
                            {
                                defaultProxy.Attributes.Remove("repost");
                            }
                            else
                            {
                                defaultProxy.Attributes["repost"] = host;// setting["Host"];
                            }
                            if (String.IsNullOrEmpty(setting["Port"]))
                            {
                                defaultProxy.Attributes.Remove("port");
                            }
                            else
                            {
                                defaultProxy.Attributes["port"] = setting["Port"];
                            }
                            // if (String.IsNullOrEmpty(setting["Server"]))
                            // {
                            //     defaultProxy.Attributes.Remove("server");
                            // }
                            // else
                            // {
                            //     defaultProxy.Attributes["server"] = setting["Server"];
                            // }
                            if (String.IsNullOrEmpty(setting["Limit"]))
                            {
                                defaultProxy.Attributes.Remove("limit");
                            }
                            else
                            {
                                defaultProxy.Attributes["limit"] = setting["Limit"];
                            }
                            configs.Providers.RemoveWhere(r => r.Type == "proxy");
                            configs.Add(defaultProxy);
                            UMC.Data.Reflection.Configuration("host", configs);
                        }
                        else
                        {

                            var proxyCfg = proxyConfig[porxy];
                            if (proxyCfg == null)
                            {
                                porxy = setting["Host"];
                                proxyCfg = Provider.Create(porxy, "Proxy");
                            }
                            proxyCfg.Attributes["title"] = setting["Title"];

                            proxyCfg.Attributes["port"] = setting["Port"];
                            int Limit = Utility.IntParse(setting["Limit"], 0);
                            if (Limit > 0)
                            {
                                proxyCfg.Attributes["limit"] = Limit.ToString();
                            }
                            else
                            {
                                proxyCfg.Attributes.Remove("limit");
                            }
                            proxyConfig.Add(proxyCfg);
                            UMC.Data.Reflection.Configuration("proxy", proxyConfig);
                        }
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "Unix":
                    hosts.Add(UMC.Data.Provider.Create("unix", "unix"));
                    UMC.Data.Reflection.Configuration("host", hosts);
                    this.Context.Send($"{request.Model}.{request.Command}", true);
                    break;
                case "QPS":
                    {
                        var setting = this.AsyncDialog("QPS", r =>
                        {
                            var fm = new UIFormDialog() { Title = "并发数" };
                            fm.AddText("网址", "Host", String.Empty);
                            fm.AddText("并发数", "QPS", String.Empty);
                            fm.Submit("确认", $"{request.Model}.{request.Command}");
                            return fm;
                        });
                        try
                        {
                            var fs = setting["Host"];
                            if (fs.StartsWith("http://") || fs.StartsWith("https://"))
                            {
                                NetProxy.QPS(new Uri(fs), Utility.IntParse(setting["QPS"], 0));
                            }
                            else
                            {
                                NetProxy.QPS(new Uri($"http://{fs}"), Utility.IntParse(setting["QPS"], 0));
                            }
                        }
                        catch
                        {
                            this.Prompt("网址格式不正确");
                        }
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "DNS":
                    {
                        var setting = this.AsyncDialog("DNS", r =>
                        {
                            var fm = new UIFormDialog() { Title = "DNS解释" };
                            fm.AddText("域名", "Host", String.Empty);
                            fm.AddText("解释IP", "IP", String.Empty);
                            fm.Submit("确认", $"{request.Model}.{request.Command}");
                            return fm;
                        });


                        string host = setting["Host"];//"example.com";
                        var chechHost = host;
                        if (chechHost.StartsWith("*."))
                        {
                            chechHost = chechHost.Substring(2);
                        }
                        if (Regex.IsMatch(chechHost, @"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$", RegexOptions.IgnoreCase) == false)
                        {
                            this.Prompt("非有效的域名");
                        }
                        var ip = setting["IP"];

                        if (System.Net.IPAddress.TryParse(ip, out var address))
                        {
                            UMC.Net.NetProxy.DNS(host, address);
                        }
                        else if (ip == "dns6")
                        {
                            UMC.Net.NetProxy.DNS(host, NetProxy.DNSType.DNS | NetProxy.DNSType.IP6);
                        }
                        else if (ip == "dns")
                        {
                            UMC.Net.NetProxy.DNS(host, NetProxy.DNSType.DNS);
                        }
                        else
                        {
                            this.Prompt("不是有效的IP地址");
                        }

                        Utility.SaveDNS();
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "Assist":
                    {
                        var Config = this.AsyncDialog("Domain", r =>
                        {
                            var fm = new UIFormDialog() { Title = "辅助域名" };

                            fm.AddText("域名", "domain", String.Empty);
                            fm.AddCheckBox("", "Auth", "_").Put("关闭此域名的人机效验", "Close");
                            fm.Submit("确认添加", $"{request.Model}.{request.Command}");
                            return fm;
                        });
                        var Domain = Config["domain"];

                        if (Regex.IsMatch(Domain, @"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$", RegexOptions.IgnoreCase) == false)
                        {
                            this.Prompt("非有效的域名");
                        }
                        var domainValue = new StringValue(Domain);
                        if (DataFactory.Instance().Host(domainValue) != null)
                        {
                            this.Prompt("此域名已经被引用");
                        }
                        else
                        {
                            var h = new SiteHost { Host = domainValue, Root = StringValue.Empty };
                            h.IsAuthModel = Config["Auth"].Contains("Close");
                            DataFactory.Instance().Put(h);
                        }
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "AuthDomain":
                    {
                        var provider = Data.WebResource.Instance().Provider;
                        var AuthDomain = this.AsyncDialog("Domain", r =>
                        {
                            var fm = new UITextDialog(provider["auth"]) { Title = "主域名前缀" };
                            fm.Config.PlaceHolder("前缀+根域名为主域名，用“.”表示清除前缀");
                            fm.CloseEvent = $"{request.Model}.{request.Command}";
                            return fm;
                        });
                        if (AuthDomain == ".")
                        {
                            provider.Attributes.Remove("auth");
                        }
                        else
                        {
                            if (Regex.IsMatch(AuthDomain, @"^([a-z0-9]+)$", RegexOptions.IgnoreCase) == false)
                            {
                                this.Prompt("非有效的域名前缀");
                            }
                            provider.Attributes["auth"] = AuthDomain;
                        }

                        var pc = UMC.Data.Reflection.Configuration("assembly") ?? new ProviderConfiguration();

                        pc.Add(provider);
                        UMC.Data.Reflection.Configuration("assembly", pc);

                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "Domain":
                    {
                        var provider = Data.WebResource.Instance().Provider;
                        var Domains = this.AsyncDialog("Domain", r =>
                        {
                            var fm = new UIFormDialog() { Title = "网关参数" };

                            var union = provider["union"] ?? ".";
                            fm.AddText("根域名", "domain", (union == "-" ? "-" : "") + provider["domain"]).Put("tip", "当根域名以“-”为前缀，则用“-”来连接应用标识");

                            var scheme = provider["scheme"] ?? "http";
                            fm.AddCheckBox("", "scheme", "http").Put("启用HTTP转HTTPS", "https", scheme == "https");

                            fm.Submit("确认", $"{request.Model}.{request.Command}");
                            return fm;
                        });
                        var domain = Domains["domain"];
                        switch (domain[0])
                        {
                            case '-':
                            case '.':
                                if (Regex.IsMatch(domain.Substring(1), @"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$", RegexOptions.IgnoreCase) == false)
                                {
                                    this.Prompt("非有效的域名");
                                }
                                WebServlet.DomainUnion = domain[0];
                                provider.Attributes["union"] = domain.Substring(0, 1);
                                domain = domain.Substring(1);
                                break;
                            default:
                                if (Regex.IsMatch(domain, @"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$", RegexOptions.IgnoreCase) == false)
                                {
                                    this.Prompt("非有效的域名");
                                }
                                WebServlet.DomainUnion = '.';
                                provider.Attributes["union"] = ".";
                                break;
                        }

                        provider.Attributes["scheme"] = Domains["scheme"].Contains("https") ? "https" : "http";
                        provider.Attributes["domain"] = domain;


                        var pc = UMC.Data.Reflection.Configuration("assembly") ?? new ProviderConfiguration();

                        pc.Add(provider);
                        UMC.Data.Reflection.Configuration("assembly", pc);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "Share":
                    {
                        var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Prompt("当前版本未登记注册", false);
                            response.Redirect("System", "License");
                        }
                        var webr2 = new Uri(APIProxy.Uri, "Certificater").WebRequest();
                        UMC.ITME.Utility.Sign(webr2, secret);

                        var hs = JSON.Deserialize<WebMeta>(webr2.Post(new WebMeta().Put("type", "share"), out var _));
                        this.Context.Send("Clipboard", new WebMeta().Put("text", hs["text"]).Put("msg", hs["msg"]), true);

                    }

                    break;
                case "Url":
                    response.Redirect(new Uri(this.AsyncDialog("Url", r => this.Prompt("请输入Url"))));
                    break;
                case "Statement":
                    {

                        if ((request.SendValues?.ContainsKey("limit") ?? false) == false)
                        {
                            this.Context.Send(new UISectionBuilder(request.Model, request.Command, request.Arguments)

                                    .Builder(), true);
                        }

                        var webr = new Uri(APIProxy.Uri, "/UMC/System/Docs/apiumc?limit=30").WebRequest();

                        response.Redirect(JSON.Expression(webr.Get(out var _)));

                    }
                    break;
                case "VIP":
                    {
                        this.AsyncDialog("VIP", g =>
                        {
                            var ui = new UISheetDialog() { Title = "服务升级" };
                            ui.Put(new UIClick(request, "Model", "Recharge", "Code", "CName") { Text = "订购开拓专享" })
                            .Put(new UIClick(request, "BuyAll") { Text = "订购企业专享" });
                            return ui;
                        });

                    }
                    break;
                case "BuyAll":
                    response.Redirect(request.Model, request.Command, new WebMeta().Put("Model", "Recharge", "Code", "*"), true);
                    break;
                case "Site":
                    var Site = this.AsyncDialog("Site", r =>
                    {
                        return new UITextDialog(hosts.ProviderType) { Title = "服务站点" };
                    });
                    hosts.ProviderType = Site;
                    UMC.Data.Reflection.Configuration("host", hosts);
                    this.Context.Send($"{request.Model}.{request.Command}", true);
                    break;
                case "Cert":
                    {

                        var httpPorts2 = this.AsyncDialog("Cert", r =>
                        {
                            var fm = new UIFormDialog() { Title = "证书" };
                            fm.AddText("域名", "Domain", String.Empty);
                            fm.AddTextarea("公钥", "publicKey", String.Empty).Put("Rows", 10).PlaceHolder("以-----BEGIN CERTIFICATE-----开始的证书").Put("tip", "公钥证书");
                            fm.AddTextarea("私钥", "privateKey", String.Empty).Put("Rows", 10).PlaceHolder("以-----BEGIN RSA PRIVATE KEY-----开始的证书").Put("tip", "私钥证书");
                            fm.Submit("确认添加", $"{request.Model}.{request.Command}");
                            return fm;
                        });

                        var Domain = httpPorts2["Domain"];
                        var publicKey = httpPorts2["publicKey"];
                        var privateKey = httpPorts2["privateKey"];

                        X509Certificate2 x509 = null;
                        try
                        {
                            x509 = X509Certificate2.CreateFromPem(publicKey, privateKey);

                        }
                        catch
                        {
                            this.Prompt("证书不正确");
                        }
                        if (x509.NotAfter < DateTime.Now)
                        {
                            x509.Dispose();
                            this.Prompt("此证书已过期");
                        }


                        HotCache.Put(new Entities.SiteCert
                        {
                            Domain = new StringValue(Domain),
                            IsApiumc = true,
                            ExpirationTime = Utility.TimeSpan(x509.NotAfter),
                            CheckTime = Utility.TimeSpan(),
                            PrivateKey = new StringValue(privateKey),
                            PublicKey = new StringValue(publicKey)
                        });


                        Certificater.Certificates[Domain] = new Certificater(Domain, x509);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                        break;
                    }
                case "DelAssist":
                    {

                        var host = this.AsyncDialog("Domain", "none");
                        DataFactory.Instance().Delete(new SiteHost { Host = new StringValue(host) });
                        this.Context.Send($"{request.Model}.{request.Command}.Del", true);
                    }
                    break;
                case "DelDNS":
                    {
                        var host = this.AsyncDialog("Domain", "none");

                        UMC.Net.NetProxy.DNS(host, true);

                        Utility.SaveDNS();

                        this.Context.Send($"{request.Model}.{request.Command}.Del", true);

                    }
                    break;
                case "Del":
                    {
                        var host = this.AsyncDialog("Domain", "none");
                        if (Certificater.Certificates.TryRemove(host, out var _v))
                        {
                            var certs = UMC.Data.Reflection.Configuration("certs");
                            certs.Remove(host);
                            UMC.Data.Reflection.Configuration("certs", certs);

                        }
                        HotCache.Delete(new SiteCert { Domain = new StringValue(host) });

                        this.Context.Send($"{request.Model}.{request.Command}.Del", true);

                    }
                    break;
                case "ApplyCert":
                    {
                        var host = UIDialog.AsyncDialog(this.Context, "Domain", g =>
                        {
                            var fm = new UIFormDialog() { Title = "申请证书" };
                            fm.AddText("域名", "Domain", String.Empty);
                            fm.Submit("确认申请", $"{request.Model}.{request.Command}");
                            return fm;
                        });
                        // var Dcv = this.AsyncDialog("Dcv", "default");
                        if (System.Text.RegularExpressions.Regex.IsMatch(host, @"^([a-z0-9\*]([a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z0-9]{1,6}$") == false)
                        {
                            this.Prompt("域名格式不正确");
                        }

                        var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Prompt("当前版本未登记注册", false);
                            response.Redirect("System", "License");
                        }
                        var webr2 = new Uri(APIProxy.Uri, "Certificater").WebRequest();
                        UMC.ITME.Utility.Sign(webr2, secret);

                        var str = webr2.Post(new WebMeta().Put("type", "apply", "domain", host, "dcv", "default"), out var webr);

                        if (webr.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var hs = JSON.Deserialize<WebMeta>(str);
                            this.Context.Send($"{request.Model}.{request.Command}", false);
                            if (string.Equals(hs["code"], "success"))
                            {
                                response.Redirect(request.Model, request.Command, new UIConfirmDialog("正在签发证书，确认进入证书签发详情", "CSR"), new WebMeta("Domain", host), true);
                            }
                            else if (string.Equals(hs["code"], "completed"))
                            {
                                webr2.Post(new WebMeta().Put("type", "cert", "domain", host), UMC.ITME.Utility.Certificate);
                                this.Prompt(hs["msg"]);
                            }
                            else if (string.Equals(hs["code"], "verifing"))
                            {
                                response.Redirect(request.Model, request.Command, new WebMeta("Domain", host).Put("Model", "CSR"), true);

                            }
                            else if (string.Equals(hs["code"], "privateKey"))
                            {
                                response.Redirect(request.Model, request.Command, new WebMeta("Domain", host).Put("Model", "PrivateKey"), true);

                            }
                            else if (string.Equals(hs["code"], "url"))
                            {
                                var confi = new UIConfirmDialog(hs["msg"], "Url");
                                confi.Config.Put("Action", true);
                                response.Redirect(request.Model, request.Command, confi, new WebMeta("Url", hs["url"]), true);
                            }
                            else if (string.Equals(hs["code"], "vip"))
                            {
                                response.Redirect(request.Model, request.Command, new UIConfirmDialog(hs["msg"], "VIP"), true);
                            }
                            else
                            {
                                this.Prompt("提示", hs["msg"], false);
                            }

                        }
                        else
                        {
                            this.Prompt("错误", $"请确保域名“{host}”解释到服务器，并开放80端口");
                        }
                    }
                    break;
                case "CSR":
                    {
                        var host = UIDialog.AsyncDialog(this.Context, "Domain", g =>
                         {
                             var fm = new UIFormDialog() { Title = "申请证书" };
                             fm.AddText("域名", "Domain", String.Empty);
                             return fm;
                         });
                        var webr2 = new Uri(APIProxy.Uri, "Certificater").WebRequest();

                        var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Prompt("当前版本未登记注册", false);
                            response.Redirect("System", "License");
                        }
                        UMC.ITME.Utility.Sign(webr2, secret);

                        var certmodel = this.AsyncDialog("CertModel", rm =>
                        {

                            var json = webr2.Post(new WebMeta().Put("type", "info", "domain", host), out var _);

                            var hash = JSON.Deserialize<Hashtable>(json);// ?? new Hashtable();

                            if (hash == null)
                            {
                                this.Prompt(json);
                            }
                            var ui = UISection.Create(new UITitle("域名证书"));
                            if (hash.ContainsKey("isEnterprise"))
                            {
                                ui.AddCell("会员类型", hash["vip"] as string, new UIClick(request, "BuyAll"));
                            }
                            else
                            {
                                ui.AddCell("会员类型", hash["vip"] as string, new UIClick(request, "VIP"));
                            }
                            ui.AddCell("服务说明", "去了解更多权益", new UIClick(request, "Statement"));//.Header.Put("text", "公共服务");

                            var lu = ui.NewSection().AddCell("域名", hash["domain"] as string);

                            var strBtn = "从新签发";
                            if (hash.ContainsKey("order"))
                            {
                                lu.AddCell("单号", hash["order"] as string);

                                var csr = ui.NewSection();
                                switch (hash["status"] as string)
                                {
                                    case "domain_verifing":
                                        csr.AddCell("证书状态", hash["state"] as string, new UIClick(request, rm, "verifing"));
                                        break;
                                    case "check":
                                        csr.AddCell("证书状态", hash["state"] as string, new UIClick(request, rm, "check"));

                                        break;
                                    case "cname":
                                        csr.AddCell("证书状态", hash["state"] as string);
                                        csr.NewSection()//.AddCell("主域名", hash["cname"] as string)
                                         .AddCell("记录类型", "CNAME")
                                        .AddCell("主机记录", "点击复制", new UIClick(new WebMeta().Put("text", hash["auth_path"] as string)) { Key = "Clipboard" })
                                        .AddCell("记录值", "点击复制", new UIClick(new WebMeta().Put("text", hash["auth_val"] as string)) { Key = "Clipboard" })
                                        .Header.Put("text", "请在主域名解释添加如下记录");
                                        break;
                                    default:

                                        csr.AddCell("证书状态", hash["state"] as string);
                                        break;
                                }
                                if (hash.ContainsKey("expire"))
                                {
                                    csr.AddCell("证书过期", hash["expire"] as string);
                                }

                            }
                            else if (hash.ContainsKey("state"))
                            {
                                ui.NewSection().AddCell("证书状态", hash["state"] as string);
                            }

                            if (Certificater.Certificates.TryGetValue(host, out var _v))
                            {
                                if (_v.Certificate != null)
                                {
                                    var cn = _v.Certificate.Subject.Split(',').First(r => r.Trim().StartsWith("CN=")).Substring(3);
                                    if (hash.ContainsKey("expire") && hash.ContainsKey("order"))
                                    {
                                        ui.NewSection().AddCell("证书公用名", cn);
                                    }
                                    else
                                    {
                                        ui.NewSection().AddCell("证书公用名", cn).AddCell("证书过期", Utility.Expire(Utility.TimeSpan(), Utility.TimeSpan(Convert.ToDateTime(_v.Certificate.GetExpirationDateString())), "正签发"));
                                    }
                                }
                                else if (hash.ContainsKey("order"))
                                {
                                    strBtn = "下载证书";
                                }
                            }
                            else if (hash.ContainsKey("order"))
                            {
                                strBtn = "下载证书";
                            }
                            else
                            {
                                strBtn = "免费申请";


                                UIDesc desc = new UIDesc("未有证书，请申请");
                                desc.Desc("{icon}\n{desc}").Put("icon", "\uf24a");
                                desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                                ui.NewSection().Add(desc);


                            }
                            if (hash.ContainsKey("isLock"))
                            {
                                ui.NewSection().AddCell("自动续签", hash["contract"] as string);

                            }
                            else
                            {
                                ui.NewSection().AddCell("自动续签", hash["contract"] as string, new UIClick(request, "Model", "Recharge", "Code", hash["domain"] as string));

                            }




                            ui.NewSection().AddCell("联系官方", "让天才工程师为你服务", new UIClick("System", "License", "Contact"));

                            ui.UIFootBar = new UIFootBar() { IsFixed = true };
                            switch (hash["status"] as string)
                            {
                                case "cname":
                                    ui.UIFootBar.AddText(new UIEventText("验证域名记录").Click(new UIClick(request, rm, "verifing")),
                                                       new UIEventText("订阅自动续签").Click(new UIClick(request, "Model", "Recharge", "Code", hash["root"] as string)).Style(new UIStyle().BgColor()));

                                    break;
                                default:
                                    ui.UIFootBar.AddText(new UIEventText(strBtn).Click(new UIClick(request, "Model", "ApplyCert", "Domain", hash["domain"] as string)),
                                            new UIEventText("订阅自动续签").Click(new UIClick(request, "Model", "Recharge", "Code", hash["root"] as string)).Style(new UIStyle().BgColor()));
                                    break;
                            }
                            ui.SendTo(this.Context, $"{request.Model}.{request.Command}");
                        });

                        switch (certmodel)
                        {
                            case "verifing":
                                var json = webr2.Post(new WebMeta().Put("type", "verify", "domain", host), out var _);
                                var hash = JSON.Deserialize<WebMeta>(json);
                                if (String.Equals(hash?["code"], "success") == false)
                                {
                                    this.Prompt(hash["msg"]);
                                }
                                break;
                            case "check":
                                webr2.Post(new WebMeta().Put("type", "cert", "domain", host), Utility.Certificate);
                                break;
                        }
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
                case "Http":
                    var httpPort = UIDialog.AsyncDialog(this.Context, "Port", g =>
                       {
                           var fm = new UIFormDialog() { Title = "Http服务" };
                           fm.AddNumber("端口", "Port", String.Empty);
                           fm.Submit("确认", $"{request.Model}.{request.Command}");
                           return fm;
                       });
                    if (Utility.IntParse(httpPort, 0) > 0)
                    {
                        var p = UMC.Data.Provider.Create(httpPort, "http");
                        p.Attributes["port"] = httpPort;
                        hosts.Add(p);
                        UMC.Data.Reflection.Configuration("host", hosts);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    else
                    {
                        this.Prompt("请输入正确的端口号");
                    }
                    break;

                case "Recharge":
                    {
                        var Code = UIDialog.AsyncDialog(this.Context, "Code", g =>
                       {
                           var fm = new UIFormDialog() { Title = "域名" };
                           fm.AddText("域名", "Code", String.Empty);
                           return fm;
                       });
                        var ComboValue = UMC.Web.UIDialog.AsyncDialog(this.Context, "Combo", gg =>
                        {
                            var webr = new Uri(APIProxy.Uri, "Transfer").WebRequest();

                            var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
                            UMC.ITME.Utility.Sign(webr, secret);
                            var data = JSON.Deserialize<WebMeta>(webr.Post(new WebMeta().Put("type", "Cert").Put("code", Code), out var _));

                            request.Arguments["API"] = data["src"] as string;
                            var Combo = data.GetDictionary()[gg] as Array;

                            var fom = new Web.UIFormDialog() { Title = data["Title"] ?? "订阅" };
                            var style = new UIStyle();
                            style.Name("icon").Color(0x09bb07).Size(84).Font("wdk");
                            style.Name("title").Color(0x333).Size(20);
                            style.BgColor(0xfafcff).Height(200).AlignCenter();
                            var desc = new UMC.Web.WebMeta().Put("title", data["Desc"] ?? "证书自动续签服务").Put("icon", data["Icon"] ?? "\uf0ee");
                            fom.Config.Put("Header", new UIHeader().Desc(desc, "{icon}\n{title}", style));

                            if (data.ContainsKey("Text"))
                            {
                                fom.AddTextValue().Put("订阅域名", data["Text"] as string ?? Code);
                            }
                            var f = fom.AddRadio("订阅套餐", "Combo");
                            var cl = Combo.Length;
                            for (var i = 0; i < cl; i++)
                            {
                                var hash = Combo.GetValue(i) as System.Collections.Hashtable;
                                f.Put(hash["Text"] as string, hash["Value"] as string, i == cl - 1);
                            }
                            fom.Config.Put("Action", true);
                            if (data.ContainsKey("Footer"))
                            {
                                fom.AddFooter(data["Footer"]);
                            }

                            fom.Submit("确认订阅");
                            return fom;
                        });
                        var src = this.AsyncDialog("API", r =>
                        {
                            this.Prompt("支付参数不正确，请联系官方");
                        });
                        response.Redirect(new Uri($"{src}&Combo={ComboValue}&Code={Code}"));
                    }
                    break;
                case "Tcp":

                    var Tcp = this.AsyncDialog("TCP", g =>
                       {
                           var fm = new UIFormDialog() { Title = "TCP报文转发" };
                           fm.AddNumber("本地端口", "Port", String.Empty);

                           fm.AddText("服务端口", "Server", String.Empty).PlaceHolder("例如 192.0.0.2:22");
                           fm.Submit("确认", $"{request.Model}.{request.Command}");
                           return fm;
                       });

                    if (Utility.IntParse(Tcp["Port"], 0) > 0)
                    {
                        var server = Tcp["Server"].Split(":");
                        if (server.Length != 2)
                        {
                            this.Prompt("请输入正确的服务端口");
                        }
                        //(\d{1,3}\.){3}\d{1,3}

                        if (Utility.IntParse(server[1], 0) <= 0 || System.Text.RegularExpressions.Regex.IsMatch(server[0], @"(((\d)|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d)|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))") == false)
                        {

                            this.Prompt("请输入正确的服务端口");
                        }

                        var p = UMC.Data.Provider.Create(Tcp["Port"], "tcp");
                        p.Attributes["port"] = Tcp["Port"];
                        p.Attributes["server"] = Tcp["Server"];
                        hosts.Add(p);
                        UMC.Data.Reflection.Configuration("host", hosts);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    else
                    {
                        this.Prompt("请输入正确的本地端口");
                    }
                    break;
                case "Udp":

                    var udp = this.AsyncDialog("UDP", g =>
                       {
                           var fm = new UIFormDialog() { Title = "UDP报文转发" };
                           fm.AddNumber("本地端口", "Port", String.Empty);

                           fm.AddText("服务端口", "Server", String.Empty).PlaceHolder("例如 192.0.0.2:22");
                           fm.Submit("确认", $"{request.Model}.{request.Command}");
                           return fm;
                       });

                    if (Utility.IntParse(udp["Port"], 0) > 0)
                    {
                        var server = udp["Server"].Split(":");
                        if (server.Length != 2)
                        {
                            this.Prompt("请输入正确的服务端口");
                        }

                        if (Utility.IntParse(server[1], 0) <= 0 || System.Text.RegularExpressions.Regex.IsMatch(server[0], @"(((\d)|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d)|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))") == false)
                        {

                            this.Prompt("请输入正确的服务端口");
                        }

                        var p = UMC.Data.Provider.Create(udp["Port"], "udp");
                        p.Attributes["port"] = p.Name;
                        p.Attributes["server"] = udp["Server"];
                        hosts.Add(p);
                        UMC.Data.Reflection.Configuration("host", hosts);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    else
                    {
                        this.Prompt("请输入正确的本地端口");
                    }
                    break;
                case "Https":

                    var httpsPort = UIDialog.AsyncDialog(this.Context, "Port", g =>
                       {
                           var fm = new UIFormDialog() { Title = "Https服务" };
                           fm.AddNumber("端口", "Port", String.Empty);
                           fm.Submit("确认", $"{request.Model}.{request.Command}");
                           return fm;
                       });
                    if (Utility.IntParse(httpsPort, 0) > 0)
                    {
                        var p = UMC.Data.Provider.Create(httpsPort, "https");
                        p.Attributes["port"] = httpsPort;

                        hosts.Add(p);
                        UMC.Data.Reflection.Configuration("host", hosts);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    else
                    {
                        this.Prompt("请输入正确的端口号");
                    }
                    break;

                case "PrivateKey":
                    {
                        var host = this.AsyncDialog("Domain", g => this.Prompt("请输入域名"));
                        var privateKey = UIDialog.AsyncDialog(this.Context, "PrivateKey", r =>
                            {
                                var fm = new UIFormDialog() { Title = "证书私钥" };
                                fm.AddTextValue().Put("域名", host);
                                fm.AddTextarea("私钥", "PrivateKey", String.Empty).PlaceHolder("证书.key文件内容").Put("tip", "证书私钥"); ;
                                fm.Submit("确认导入", $"{request.Model}.{request.Command}");
                                return fm;
                            });

                        var webr2 = new Uri(APIProxy.Uri, "Certificater").WebRequest();

                        var json = UMC.ITME.Utility.Sign(webr2, UMC.Data.WebResource.Instance().Provider["appSecret"])
                          .Post(new WebMeta().Put("type", "cert", "domain", host), out var rese);
                        if (rese.StatusCode != System.Net.HttpStatusCode.OK)
                        {
                            this.Prompt("提示", json);
                        }
                        var cert = JSON.Deserialize<WebMeta>(json);
                        var publicKey = cert["publicKey"];
                        try
                        {
                            var x509 = X509Certificate2.CreateFromPem(publicKey, privateKey);
                            var p = UMC.Data.Provider.Create(cert["domain"], "privateKey");
                            p.Attributes["publicKey"] = publicKey;
                            p.Attributes["privateKey"] = privateKey;
                            var certs = UMC.Data.Reflection.Configuration("certs");
                            certs.Add(p);
                            Certificater.Certificates[p.Name] = new Certificater(p.Name, x509);
                            UMC.Data.Reflection.Configuration("certs", certs);
                        }
                        catch (Exception ex)
                        {
                            this.Prompt("证书错误", ex.Message);
                        }

                        this.Context.Send($"{request.Model}.{request.Command}", true);

                    }
                    break;
                default:

                    var pr = hosts[model];
                    if (pr != null)
                    {
                        hosts.Remove(model);
                        UMC.Data.Reflection.Configuration("host", hosts);
                        this.Context.Send($"{request.Model}.{request.Command}", true);
                    }
                    break;
            }

        }
    }
}